package com.keku.kplay.utils;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 小良
 * @version 1.0
 * @date 2021/3/30 11:38
 */
public class ResultModel {
    private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS";

    public static Result successResult() {
        return new Result()
                .setCode(ResultCode.SUCCESS)
                .setMsg(DEFAULT_SUCCESS_MESSAGE);
    }

    public static <T> Result<T> successResult(T data) {
        return new Result()
                .setCode(ResultCode.SUCCESS)
                .setMsg(DEFAULT_SUCCESS_MESSAGE)
                .setData(data);
    }

    public static Result failResult(String msg) {
        return new Result()
                .setCode(ResultCode.FAIL)
                .setMsg(msg);
    }

    public static Result failResult(ResultCode resultCode, String msg) {
        return new Result()
                .setCode(resultCode)
                .setMsg(msg);
    }

    public static void out(HttpServletResponse response, Result result) {
        ServletOutputStream out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            out = response.getOutputStream();
            out.write(JSONObject.toJSONString(result).getBytes());
        } catch (Exception e) {
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
